const express = require('express');
const path = require('node:path');
const pool = require(path.resolve(__dirname, '../sqlPool.js'));
const svgCaptcha = require('svg-captcha');
const jwt = require('jsonwebtoken');
const router = express.Router();

router.post('/updateUserMsg', (req, res) => {
	let sql = '';
	if (req.body.state === 'updateAvatar') {
		if (req.body.username) {
			sql = `UPDATE usermsg SET avatar=${null} WHERE username="${
				req.body.username
			}"`;
			pool.query(sql, (error, result) => {
				if (error) {
					console.log(error);
					return res.send({
						state: 'error',
					});
				} else {
					return res.send({
						state: 'ok',
					});
				}
			});
		}
	} else if (req.body.state === 'updateNickname') {
		if (req.body.username) {
			sql = `UPDATE usermsg SET nickname="违规昵称" WHERE username="${req.body.username}"`;
			pool.query(sql, (error, result) => {
				if (error) {
					console.log(error);
					return res.send({
						state: 'error',
					});
				} else {
					return res.send({
						state: 'ok',
					});
				}
			});
		}
	} else if (req.body.state === 'updateNotes') {
		if (req.body.username) {
			sql = `UPDATE usermsg SET notes="违规签名" WHERE username="${req.body.username}"`;
			pool.query(sql, (error, result) => {
				if (error) {
					console.log(error);
					return res.send({
						state: 'error',
					});
				} else {
					return res.send({
						state: 'ok',
					});
				}
			});
		}
	}
});

router.post('/getAllUserPageMsg', (req, res) => {
	if (req.body.limit) {
		let sql = `SELECT * FROM usermsg LIMIT ${req.body.limit} OFFSET ${req.body.offset}`;
		pool.query(sql, (error, result) => {
			if (error) {
				console.log(error);
				return res.send({
					state: 'error',
				});
			} else {
				return res.send({
					state: 'ok',
					data: result,
				});
			}
		});
	} else {
		return res.send({
			state: 'error',
		});
	}
});

router.post('/getAllUserLength', (req, res) => {
	let sql = `SELECT * FROM usermsg`;
	pool.query(sql, (error, result) => {
		if (error) {
			console.log(error);
			return res.send({
				state: 'error',
			});
		} else {
			res.send({
				state: 'ok',
				data: result.length,
			});
		}
	});
});

router.post('/cancelUserFollow', (req, res) => {
	if (req.body.followmsgobj && req.body.username) {
		// delete from exam_result where name = '唐三藏';
		let followMsgObj = {
			userClass: req.body.followmsgobj.userType,
			userId: req.body.followmsgobj.userId,
		};
		let sql = `SELECT * FROM followmsg WHERE username="${req.body.username}"`;
		pool.query(sql, (error, result) => {
			if (error) {
				console.log(error);
				return res.send({
					state: 'error',
				});
			} else {
				result.forEach((item) => {
					if (
						JSON.parse(item.followmsgobj).userClass ===
							followMsgObj.userClass &&
						JSON.parse(item.followmsgobj).userId ===
							followMsgObj.userId
					) {
						sql = `DELETE FROM followmsg WHERE id=${item.id}`;
						pool.query(sql, (error, result) => {
							if (error) {
								console.log(error);
								return res.send({
									state: 'error',
								});
							} else {
								return res.send({
									state: 'ok',
								});
							}
						});
					}
				});
			}
		});
	}
});

router.post('/getUserMsgById', (req, res) => {
	if (req.body.id && req.body.userType) {
		let sql = `SELECT * FROM ${req.body.userType} WHERE id=${req.body.id}`;
		pool.query(sql, (error, result) => {
			if (error) {
				console.log(error);
				return res.send({
					state: 'error',
				});
			} else {
				return res.send({
					state: 'ok',
					data: result,
				});
			}
		});
	}
});

router.post('/getUserBeingFollowTotal', (req, res) => {
	if (req.body.userType && req.body.id) {
		let sql = `SELECT * FROM followmsg`;
		let beingFollowList = [];
		let itemObj = null;
		pool.query(sql, (error, result) => {
			if (error) {
				console.log(error);
				return res.send({
					state: 'error',
				});
			} else {
				result.forEach((item) => {
					itemObj = JSON.parse(item.followmsgobj);
					if (req.body.userType === 'userOk') {
						if (
							itemObj.userClass === 'usermsg' &&
							itemObj.userId === req.body.id
						) {
							beingFollowList.push({
								username: item.username,
								userType: 'usermsg',
							});
							itemObj = null;
						}
					}
					if (req.body.userType === 'managerOk') {
						if (
							itemObj.userClass === 'managermsg' &&
							itemObj.userId === req.body.id
						) {
							beingFollowList.push({
								username: item.username,
								userType: 'managermsg',
							});
							itemObj = null;
						}
					}
				});

				return res.send({
					state: 'ok',
					total: beingFollowList.length,
				});
			}
		});
	}
});

router.post('/getUserBeingFollow', (req, res) => {
	if (req.body.userType && req.body.id) {
		if (!req.body.limit) {
			let sql = `SELECT * FROM followmsg`;
			let beingFollowList = [];
			let itemObj = null;
			pool.query(sql, (error, result) => {
				if (error) {
					console.log(error);
					return res.send({
						state: 'error',
					});
				} else {
					result.forEach((item) => {
						itemObj = JSON.parse(item.followmsgobj);
						if (req.body.userType === 'userOk') {
							if (
								itemObj.userClass === 'usermsg' &&
								itemObj.userId === req.body.id
							) {
								beingFollowList.push({
									username: item.username,
									userType: 'usermsg',
								});
								itemObj = null;
							}
						}
						if (req.body.userType === 'managerOk') {
							if (
								itemObj.userClass === 'managermsg' &&
								itemObj.userId === req.body.id
							) {
								beingFollowList.push({
									username: item.username,
									userType: 'managermsg',
								});
								itemObj = null;
							}
						}
					});

					return res.send({
						state: 'ok',
						data: beingFollowList,
					});
				}
			});
		} else {
			let sql = `SELECT * FROM followmsg`;
			let beingFollowList = [];
			let itemObj = null;
			pool.query(sql, (error, result) => {
				if (error) {
					console.log(error);
					return res.send({
						state: 'error',
					});
				} else {
					result.forEach((item) => {
						itemObj = JSON.parse(item.followmsgobj);
						if (req.body.userType === 'userOk') {
							if (
								itemObj.userClass === 'usermsg' &&
								itemObj.userId === req.body.id
							) {
								beingFollowList.push({
									username: item.username,
									userType: 'usermsg',
								});
								itemObj = null;
							}
						}
						if (req.body.userType === 'managerOk') {
							if (
								itemObj.userClass === 'managermsg' &&
								itemObj.userId === req.body.id
							) {
								beingFollowList.push({
									username: item.username,
									userType: 'managermsg',
								});
								itemObj = null;
							}
						}
					});

					return res.send({
						state: 'ok',
						data: beingFollowList.slice(
							req.body.offset,
							req.body.limit + req.body.offset
						),
					});
				}
			});
		}
	}
});

router.post('/getUserFollowTotal', (req, res) => {
	if (req.body.username) {
		let sql = `SELECT * FROM followmsg WHERE username='${req.body.username}'`;
		let itemObj = null;
		let fansList = [];
		pool.query(sql, (error, result) => {
			if (error) {
				console.log(error);
				return res.send({
					state: 'error',
				});
			} else {
				result.forEach((item) => {
					itemObj = JSON.parse(item.followmsgobj);
					fansList.push({
						userId: itemObj.userId,
						userType: itemObj.userClass,
					});
				});

				return res.send({
					state: 'ok',
					total: fansList.length,
				});
			}
		});
	}
});

router.post('/getUserFollow', (req, res) => {
	if (req.body.username) {
		if (!req.body.limit) {
			let sql = `SELECT * FROM followmsg WHERE username='${req.body.username}'`;
			let itemObj = null;
			let fansList = [];
			pool.query(sql, (error, result) => {
				if (error) {
					console.log(error);
					return res.send({
						state: 'error',
					});
				} else {
					result.forEach((item) => {
						itemObj = JSON.parse(item.followmsgobj);
						fansList.push({
							userId: itemObj.userId,
							userType: itemObj.userClass,
						});
					});
					return res.send({
						state: 'ok',
						data: fansList,
					});
				}
			});
		} else {
			let sql = `SELECT * FROM followmsg WHERE username='${req.body.username}' LIMIT ${req.body.limit} OFFSET ${req.body.offset}`;
			let itemObj = null;
			let fansList = [];
			pool.query(sql, (error, result) => {
				if (error) {
					console.log(error);
					return res.send({
						state: 'error',
					});
				} else {
					result.forEach((item) => {
						itemObj = JSON.parse(item.followmsgobj);
						fansList.push({
							userId: itemObj.userId,
							userType: itemObj.userClass,
						});
					});
					return res.send({
						state: 'ok',
						data: fansList,
					});
				}
			});
		}
	}
});

router.post('/judgeFollowExist', (req, res) => {
	if (req.body.username && req.body.userId && req.body.myusername) {
		let sql = `SELECT * FROM usermsg WHERE username='${req.body.username}' AND id=${req.body.userId}`;
		pool.query(sql, (error, result) => {
			if (error || result.length === 0) {
				let sql = `SELECT * FROM managermsg WHERE username='${req.body.username}' AND id=${req.body.userId}`;
				pool.query(sql, (error, result) => {
					if (error || result.length === 0) {
						console.log(error);
						return res.send({
							state: 'error',
						});
					} else {
						let userClass = 'managermsg';
						let userId = req.body.userId;
						let follow = JSON.stringify({
							userClass,
							userId,
						});
						sql = `SELECT * FROM followmsg WHERE username='${req.body.myusername} AND 'followmsgobj='${follow}'`;
						pool.query(sql, (error, result) => {
							if (error || result.length === 0) {
								return res.send({
									state: 'noexist',
								});
							} else {
								return res.send({
									state: 'exist',
								});
							}
						});
					}
				});
			} else {
				let userClass = 'usermsg';
				let userId = req.body.userId;
				let follow = JSON.stringify({
					userClass,
					userId,
				});
				sql = `SELECT * FROM followmsg WHERE username='${req.body.myusername}' AND followmsgobj='${follow}'`;
				pool.query(sql, (error, result) => {
					if (error || result.length === 0) {
						return res.send({
							state: 'noexist',
						});
					} else {
						return res.send({
							state: 'exist',
						});
					}
				});
			}
		});
	}
});

router.post('/addUserFollow', (req, res) => {
	if (req.body.username && req.body.myusername) {
		let sql = `SELECT id FROM usermsg WHERE username='${req.body.username}'`;
		pool.query(sql, (error, result) => {
			if (error || result.length === 0) {
				sql = `SELECT id FROM managermsg WHERE username='${req.body.username}'`;
				pool.query(sql, (error, result) => {
					if (error || result.length === 0) {
						return res.send({
							state: 'error',
						});
					} else {
						let userClass = 'managermsg';
						let userId = result[0].id;
						let follow = JSON.stringify({
							userClass,
							userId,
						});
						sql = `INSERT INTO followmsg(username,followmsgobj) VALUES('${req.body.myusername}','${follow}')`;
						pool.query(sql, (error, result) => {
							if (error) {
								console.log(error);
								return res.send({
									state: 'error',
								});
							} else {
								return res.send({
									state: 'ok',
								});
							}
						});
					}
				});
			} else {
				let userClass = 'usermsg';
				let userId = result[0].id;
				let follow = JSON.stringify({
					userClass,
					userId,
				});
				sql = `INSERT INTO followmsg(username,followmsgobj) VALUES('${req.body.myusername}','${follow}')`;
				pool.query(sql, (error, result) => {
					if (error) {
						console.log(error);
						return res.send({
							state: 'error',
						});
					} else {
						return res.send({
							state: 'ok',
						});
					}
				});
			}
		});
	} else {
		return res.send({
			state: 'error',
		});
	}
});

router.post('/updateUserPassword', (req, res) => {
	if (req.body.username && req.body.password) {
		let sql = `UPDATE usermsg SET password='${req.body.password}' WHERE username='${req.body.username}'`;
		pool.query(sql, (error, result) => {
			if (error || result.changedRows === 0) {
				sql = `UPDATE managermsg SET password='${req.body.password}' WHERE username='${req.body.username}'`;
				pool.query(sql, (error, result) => {
					if (error || result.changedRows === 0) {
						console.log(error);
						return res.send({
							state: 'error',
						});
					} else {
						return res.send({
							state: 'ok',
						});
					}
				});
			} else {
				return res.send({
					state: 'ok',
				});
			}
		});
	} else {
		return res.send({
			state: 'error',
		});
	}
});

router.post('/updateUserSign', (req, res) => {
	if (req.body.username && req.body.notes) {
		let sql = `UPDATE usermsg SET notes='${req.body.notes}' WHERE username='${req.body.username}'`;
		pool.query(sql, (error, result) => {
			if (error || result.changedRows === 0) {
				sql = `UPDATE managermsg SET notes='${req.body.notes}' WHERE username='${req.body.username}'`;
				pool.query(sql, (error, result) => {
					if (error || result.changedRows === 0) {
						console.log(error);
						return res.send({
							state: 'error',
						});
					} else {
						return res.send({
							state: 'ok',
						});
					}
				});
			} else {
				return res.send({
					state: 'ok',
				});
			}
		});
	} else {
		return res.send({
			state: 'error',
		});
	}
});

router.post('/updateUserSex', (req, res) => {
	if (req.body.username && req.body.gender) {
		let sql = `UPDATE usermsg SET gender='${req.body.gender}' WHERE username='${req.body.username}'`;
		pool.query(sql, (error, result) => {
			if (error || result.changedRows === 0) {
				sql = `UPDATE managermsg SET gender='${req.body.gender}' WHERE username='${req.body.username}'`;
				pool.query(sql, (error, result) => {
					if (error || result.changedRows === 0) {
						console.log(error);
						return res.send({
							state: 'error',
						});
					} else {
						return res.send({
							state: 'ok',
						});
					}
				});
			} else {
				return res.send({
					state: 'ok',
				});
			}
		});
	} else {
		return res.send({
			state: 'error',
		});
	}
});

router.post('/updateUserNickname', (req, res) => {
	if (req.body.nickname && req.body.username) {
		let sql = `UPDATE usermsg SET nickname='${req.body.nickname}' WHERE username='${req.body.username}'`;
		pool.query(sql, (error, result) => {
			if (error || result.changedRows === 0) {
				sql = `UPDATE managermsg SET nickname='${req.body.nickname}' WHERE username='${req.body.username}'`;
				pool.query(sql, (error, result) => {
					if (error || result.changedRows === 0) {
						console.log(error);
						return res.send({
							state: 'error',
						});
					} else {
						return res.send({
							state: 'ok',
						});
					}
				});
			} else {
				return res.send({
					state: 'ok',
				});
			}
		});
	} else {
		return res.send({
			state: 'error',
		});
	}
});

router.post('/none', (req, res) => {
	return res.send({
		state: 'ok',
	});
});

router.post('/updateUserAvatar', (req, res) => {
	if (req.body.imgUrl && req.body.username) {
		let sql = `UPDATE usermsg SET avatar="${req.body.imgUrl}" WHERE username='${req.body.username}'`;
		pool.query(sql, (error, result) => {
			if (error || result.changedRows === 0) {
				sql = `UPDATE managermsg SET avatar="${req.body.imgUrl}" WHERE username='${req.body.username}'`;
				pool.query(sql, (error, result) => {
					if (error || result.changedRows === 0) {
						console.log(error);
						return res.send({
							state: 'error',
						});
					} else {
						return res.send({
							state: 'ok',
						});
					}
				});
			} else {
				console.log(result);
				return res.send({
					state: 'ok',
				});
			}
		});
	}
});

router.post('/registUser', (req, res) => {
	if (req.body.username && req.body.password) {
		let date = new Date();
		date = JSON.stringify(date);
		let sql = `INSERT INTO usermsg (username,password,registdate,state) VALUES('${req.body.username}','${req.body.password}','${date}',"fulfilled")`;
		pool.query(sql, (error, result) => {
			if (error) {
				console.log(error);
				return res.send({
					state: 'error',
				});
			} else {
				return res.send({
					state: 'ok',
				});
			}
		});
	} else {
		return res.send({
			state: 'error',
		});
	}
});

router.post('/exist', (req, res) => {
	if (req.body.username) {
		let sql = `SELECT username FROM usermsg WHERE username='${req.body.username}'`;
		pool.query(sql, (error, result) => {
			if (error) {
				console.log(error);
				return res.send({
					state: 'error',
				});
			}
			if (result[0]) {
				return res.send({
					state: 'exist',
				});
			} else {
				return res.send({
					state: 'absent',
				});
			}
		});
	}
});

router.post('/login', (req, res) => {
	if (req.body.state === 'validate') {
		let sql = 'SELECT username,password FROM userMsg';
		pool.query(sql, (error, result) => {
			if (error) {
				console.log(error);
				return res.send({
					state: 'error',
				});
			}
			for (let item of result) {
				if (
					item.username === req.body.username &&
					item.password === req.body.password
				) {
					return res.send({
						state: 'userOk',
					});
				}
			}
			sql = 'SELECT username,password FROM managerMsg';
			pool.query(sql, (error, result) => {
				if (error) {
					return res.send({
						state: 'error',
					});
				}
				for (let item of result) {
					if (
						item.username === req.body.username &&
						item.password === req.body.password
					) {
						return res.send({
							state: 'managerOk',
						});
					}
				}
				return res.send({
					state: 'none',
				});
			});
		});
	}
});

router.get('/createCode', (req, res) => {
	let svg = svgCaptcha.create({
		size: 6, //验证码长度
		noise: 2, //干扰线条数目
		width: 300, //宽度
		height: 50, //高度
		inverse: false, // 翻转颜色
		fontSize: 65, // 字体大小
		color: true, // 验证码字符颜色（需设置背景色）
		background: '#ccc', // 背景
	});
	// 一个是data  验证码图片
	// 一个是text  验证码途中中的码

	const token = jwt.sign({ code: svg.text }, 'makinohara', {
		expiresIn: '60s',
	});

	res.type('json'); // 响应的类型
	res.send({
		state: 'ok',
		token,
		data: svg.data,
	});
});

router.post('/verifyCode', (req, res) => {
	try {
		const decodeData = jwt.verify(req.body.token, 'makinohara');
		if (decodeData.code === req.body.code) {
			return res.send({
				state: 'ok',
			});
		} else {
			throw new Error('验证码错误');
		}
	} catch (error) {
		return res.send({
			state: 'error',
		});
	}
});

router.post('/getUserMsg', (req, res) => {
	if (req.body.state === 'singleUser') {
		let { username, password } = req.body;
		if (username && password) {
			let sql = `SELECT * FROM userMsg WHERE username="${username}" AND password="${password}"`;
			pool.query(sql, (error, result) => {
				if (!error && result[0]) {
					return res.send({
						state: 'ok',
						data: result[0],
					});
				} else {
					sql = `SELECT * FROM managerMsg WHERE username="${username}" AND password="${password}"`;
					pool.query(sql, (error, result) => {
						if (error) {
							console.log(error);
							return res.send({
								state: 'none',
							});
						} else {
							return res.send({
								state: 'ok',
								data: result[0],
							});
						}
					});
				}
			});
		} else {
			return res.send({
				state: 'error',
			});
		}
	} else if (req.body.state === 'basedUsername') {
		if (req.body.username) {
			let sql = `SELECT id,nickname,avatar,notes,registdate,gender FROM usermsg WHERE username='${req.body.username}'`;
			pool.query(sql, (error, result) => {
				if (error) {
					console.log(error);
					return res.send({
						state: 'error',
					});
				}
				if (result[0]) {
					return res.send({
						state: 'ok',
						data: result[0],
					});
				} else {
					sql = `SELECT id,nickname,avatar,notes,registdate,gender FROM managermsg WHERE username='${req.body.username}'`;
					pool.query(sql, (error, result) => {
						if (error) {
							console.log(error);
							return res.send({
								state: 'error',
							});
						}
						if (result[0]) {
							return res.send({
								state: 'ok',
								data: result[0],
							});
						} else {
							return res.send({
								state: 'error',
							});
						}
					});
				}
			});
		} else {
			return res.send({
				state: 'error',
			});
		}
	}
});

module.exports = router;
